package com.tunan.utils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tunan.common.constant.TokenConstant;
import com.tunan.persistence.model.LsjToken;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisException;

@Component
public class RedisUtils {
	@Autowired
	private JedisPool jedisPool;

	// true：服务器在线，false：服务不在线
	private boolean redisLived;

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setRedisLived(boolean redisLived) {
		this.redisLived = redisLived;
	}

	public boolean isRedisLived() {
		return redisLived;
	}

	/*
	 * 将token写入redis
	 */
	public boolean token2Redis(String value, LsjToken token) {
		Jedis jedis = null;
		Transaction multi = null;
		try {
			jedis = jedisPool.getResource();
			if (StringUtils.isEmpty(token.getAccessToken())) {
				value = jedis.get(token.getFreshToken());
				multi = jedis.multi();
			} else {
				multi = jedis.multi();
				multi.setex(token.getFreshToken(), TokenConstant.FRESH_TOKEN_LIVE,
						StringUtils.isNotEmpty(value) ? value : "没有数据");
			}
			multi.setex(token.getFreshToken().substring(0, token.getFreshToken().length() - 1),
					TokenConstant.ACCESS_TOKEN_LIVE, StringUtils.isEmpty(value) ? "没有数据" : value);
			return multi.exec().parallelStream().filter(m -> "OK".equals(m)).count() > 0;
		} catch (JedisException e) {
			if (multi != null) {
				multi.discard();
			}
			throw new JedisException(e);
		} finally {
			jedisClose(jedis);
		}
	}

	// 关闭JEDIS
	public void jedisClose(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}

	// 检查key是否存在
	public Boolean isExists(String key) {
		Jedis jedis = jedisPool.getResource();
		Boolean exists = jedis.exists(key);
		jedisClose(jedis);
		return exists;
	}

	// 检查REDIS服务是否存在
	public String isLive() {
		Jedis jedis = jedisPool.getResource();
		String pin = jedis.ping();
		jedisClose(jedis);
		return pin;
	}

	// 删除
	public void delFromKey(String freshtoken) {
		Jedis jedis = jedisPool.getResource();
		jedis.del(freshtoken);
		jedisClose(jedis);
	}
}
